const {
  CurrencyShopModel
} = require('../../../utils/currencyshop-model.js')
const {
  MemberModel
} = require('../../../utils/member-model.js')
const memberModel = new MemberModel()
const currencyShopModel = new CurrencyShopModel()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopName: '',
    shopId: '',
    currency: {},
    number: '1',
    productMoney: '0.00',
    totalMoney: {
      price: 0,
      int: '0',
      float: '00'
    },
    orderInfo: {},
    gifts: [],
    couponNum: 0,
    selectCoupon: '',
    couponPrice: '0.00',
    couponDiscount: '',
    fullDiscount: '',
    fullDiscountPrice: '',
    fullReduction: '',
    authShow: false,
    paydisabled: false,
    selectCouponType: false,
    numShow: false,
    payType: '',
    svipShow: false,
    shopAddress: '', //门店地址
    type: ''
  },

  decrease() {
    const number = +this.data.number
    this.setData({
      selectCoupon: ''
    })
    if (number > 1) {
      this.setData({
        number: number - 1 + ''
      })
      this.getOrderInfo()
    }
  },
  increase() {
    const number = +this.data.number
    this.setData({
      selectCoupon: ''
    })
    if (number < 999) {
      this.setData({
        number: number + 1 + ''
      })
      this.getOrderInfo()
    }
  },
  inputNum(event) {
    this.setData({
      selectCoupon: ''
    })
    if (event.detail.value === '' || event.detail.value === '0') {
      wx.showToast({
        title: '请填写正确数量',
        icon: 'none'
      })
      this.setData({
        number: '1'
      })
    } else {
      this.setData({
        number: event.detail.value
      })
    }
    this.getOrderInfo()
  },
  formatItem() {
    const currency = this.data.currency
    return {
      productType: currency.productType,
      goodType: currency.goodType,
      price: currency.price,
      productId: currency.id,
      quantity: +this.data.number,
      productSku: currency.productSku || '',
    }
  },
  goSelectCoupon() {
    if (this.data.couponNum) {
      wx.reportAnalytics('currency_coupon')
      let item = this.formatItem()
      const selectCoupon = this.data.selectCoupon
      const assetId = selectCoupon ? selectCoupon.assetId : ''
      const currency = this.data.currency
      if (this.data.type == '1') {
        item = {
          packageFlag: '0',
          quantity: +this.data.number,
          productSku: currency.gameCouponCode || ''
        }
      } else if (this.data.type == '2') {
        item = {
          packageFlag: '1',
          quantity: +this.data.number,
          productSku: currency.pkgCode || '',
          productId: currency.id
        }
      }
      wx.navigateTo({
        url: `/pages/currencyShop/selectCoupon/index?shopId=${this.data.shopId}&items=${JSON.stringify(item)}&assetId=${assetId}&type=${this.data.type}`,
      })
    }
  },
  formSubmit(e) {
    if (app.globalData.isLogin) {
      wx.reportAnalytics('currency_pay')
      this.setData({
        paydisabled: true
      })
      memberModel.userMessage({
        formIds: [e.detail.formId],
        merchantId: wx.getStorageSync('merchantId')
      }).then(() => {
        this.wechatPay()
      }).catch(() => {
        this.wechatPay()
      })
    } else {
      this.setData({
        authShow: true
      })
    }
  },
  svipSubmit() {
    this.setData({
      svipShow: !this.data.svipShow
    })
  },
  wechatPay() {
    const merchantId = wx.getStorageSync('merchantId')
    const item = this.formatItem()
    let params = {
      merchantId,
      items: [item],
      shopId: this.data.shopId,
      payPlatform: 'WECHAT_MALL',
      orderType: 'GAME_CURRENCY'
    }
    const selectCoupon = this.data.selectCoupon
    let coupon = {}
    if (selectCoupon) {
      params.couponId = selectCoupon.refId
      params.couponAssertId = selectCoupon.assetId
      params.couponMemberId = selectCoupon.memberId
      coupon.couponId = selectCoupon.refId
      coupon.couponAssertId = selectCoupon.assetId
      coupon.couponMemberId = selectCoupon.memberId
    }
    // 创建订单
    const currency = this.data.currency
    let requestOrder = null;

    if (this.data.type == 1) {
      requestOrder = currencyShopModel.orderUnionCreate({
        merchantId,
        items: [{
          packageFlag: '0',
          quantity: +this.data.number,
          productSku: currency.gameCouponCode || '',
          // productId: currency.id,
        }],
        shopId: this.data.shopId,
        payPlatform: 'WECHAT_MALL',
        busType: 'CASH_GAME_COUPON',
        bizCode: '1161030',
        ...coupon
      })
    } else if (this.data.type == 2) {
      requestOrder = currencyShopModel.orderUnionCreate({
        merchantId,
        items: [{
          packageFlag: '1',
          quantity: +this.data.number,
          productSku: currency.pkgCode || '',
          productId: currency.id,
        }],
        shopId: this.data.shopId,
        payPlatform: 'WECHAT_MALL',
        busType: 'CASH_PKG_GAME_COUPON',
        bizCode: '1131035',
        ...coupon
      })
    } else if (this.data.payType == "PKG_SVIP") {
      // requestOrder = currencyShopModel.svipCreateOrder(params)
      requestOrder = currencyShopModel.orderUnionCreate({
        merchantId,
        items: [{
          packageFlag: '1',
          quantity: +this.data.number,
          productSku: currency.productSku || '',
          productId: currency.id,
        }],
        shopId: this.data.shopId,
        payPlatform: 'WECHAT_MALL',
        busType: 'SVIP',
        bizCode: '1131130',
        ...coupon
      })
    } else {
      requestOrder = currencyShopModel.createOrder(params)
    }
    return new Promise((resolve, reject) => {
      requestOrder.then(({
        orderCode
      }) => {
        // 创建支付订单
        currencyShopModel.createPayOrder({
          merchantId,
          shopId: this.data.shopId,
          orderCode,
          channel: 'WEIXIN',
          payMethod: 'WAP_PAY'
        }).then(({
          payInfo
        }) => {
          this.setData({
            paydisabled: false
          })
          wx.requestPayment({
            timeStamp: payInfo.timeStamp,
            nonceStr: payInfo.nonceStr,
            package: payInfo.package,
            signType: payInfo.signType,
            paySign: payInfo.paySign,
            success: () => {
              var that = this;
              wx.reportAnalytics('currency_pay_succ')
              that.setData({
                selectCoupon: ''
              }, function () {
                wx.navigateTo({
                  url:`/pages/currencyShop/buyComplete/index?orderCode=${orderCode}&shopId=${that.data.shopId}`
                })
              })
            },
            fail: () => {
              wx.reportAnalytics('currency_pay_fail')
            }
          })
        }).catch(err => {
          wx.reportAnalytics('currency_pay_fail')
          this.setData({
            paydisabled: false
          })
          wx.showToast({
            title: `${err.error}`,
            icon: 'none'
          })
        })
      }).catch(err => {
        wx.reportAnalytics('currency_pay_fail')
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    })
  },


  getOrderInfo() {
    const merchantId = wx.getStorageSync('merchantId')
    const item = this.formatItem()
    let params = {
      merchantId,
      shopId: this.data.shopId,
      items: [item],
      payPlatform: 'WECHAT_MALL'
    }
    const selectCoupon = this.data.selectCoupon
    if (selectCoupon) {
      params.couponId = selectCoupon.refId
      params.couponAssertId = selectCoupon.assetId
      params.couponMemberId = selectCoupon.memberId
      this.getCouponOrder(params)
    } else {
      if (app.globalData.isLogin && !this.data.selectCouponType) {
        this.getCoupon(params);
      } else {
        this.getCouponOrder(params)
      }
    }

  },

  getCoupon(paramsdata) {
    let param = paramsdata;
    const item = this.formatItem()
    const merchantId = wx.getStorageSync('merchantId')
    return new Promise((resolve, reject) => {
      let request
      const currency = this.data.currency
      if (this.data.type == 1) {
        request = currencyShopModel.orderUnionCouponQuery({
          merchantId,
          items: [{
            packageFlag: '0',
            quantity: +this.data.number,
            productSku: currency.gameCouponCode || '',
            // productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'CASH_GAME_COUPON',
          bizCode: '1161030'
        })
      } else if (this.data.type == 2) {
        request = currencyShopModel.orderUnionCouponQuery({
          merchantId,
          items: [{
            packageFlag: '1',
            quantity: +this.data.number,
            productSku: currency.pkgCode || '',
            productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'CASH_PKG_GAME_COUPON',
          bizCode: '1131035'
        })
      } else if (this.data.payType == "PKG_SVIP") {
        request = currencyShopModel.orderUnionCouponQuery({
          merchantId,
          items: [{
            packageFlag: '1',
            quantity: +this.data.number,
            productSku: currency.productSku || '',
            productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'SVIP',
          bizCode: '1131130'
        })
      } else {
        request = currencyShopModel.getCouponList({
          merchantId,
          shopId: this.data.shopId,
          items: [item],
          payPlatform: 'WECHAT_MALL'
        })
      }
      request.then(data => {
        data = data || []
        this.setData({
          couponNum: data.length,
          // 进页面自动选择优惠券
          // selectCoupon: this.data.selectCoupon ? this.data.selectCoupon : (data[0] || '')
        }, function () {
          const selectCoupon = this.data.selectCoupon
          if (selectCoupon) {
            param.couponId = selectCoupon.refId
            param.couponAssertId = selectCoupon.assetId
            this.getCouponOrder(param)
          } else {
            this.getCouponOrder(param)
          }
        })
        resolve(data)
      }).catch(err => {
        this.getCouponOrder(param)
        reject(err)
      })
    })
  },


  getCouponOrder(params) {
    let request = null
    if (app.globalData.isLogin) {
      const merchantId = wx.getStorageSync('merchantId')
      const currency = this.data.currency
      if (this.data.type == 1) {
        request = currencyShopModel.orderUnionQuery({
          merchantId,
          items: [{
            packageFlag: '0',
            quantity: +this.data.number,
            productSku: currency.gameCouponCode || '',
            // productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'CASH_GAME_COUPON',
          bizCode: '1161030',
          couponId: params.couponId,
          couponAssertId: params.couponAssertId,
          couponMemberId: params.couponMemberId
        })
      } else if (this.data.type == 2) {
        request = currencyShopModel.orderUnionQuery({
          merchantId,
          items: [{
            packageFlag: '1',
            quantity: +this.data.number,
            productSku: currency.pkgCode || '',
            productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'CASH_PKG_GAME_COUPON',
          bizCode: '1131035',
          couponId: params.couponId,
          couponAssertId: params.couponAssertId,
          couponMemberId: params.couponMemberId
        })
      } else if (this.data.payType == "PKG_SVIP") {
        request = currencyShopModel.orderUnionQuery({
          merchantId,
          items: [{
            packageFlag: '1',
            quantity: +this.data.number,
            productSku: currency.productSku || '',
            productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'SVIP',
          bizCode: '1131130',
          couponId: params.couponId,
          couponAssertId: params.couponAssertId,
          couponMemberId: params.couponMemberId
        })
      } else {
        request = currencyShopModel.getOrderInfo(params)
      }
    } else {
      const merchantId = wx.getStorageSync('merchantId')
      const currency = this.data.currency
      if (this.data.type == 1) {
        request = currencyShopModel.orderUnloginUnionQuery({
          merchantId,
          items: [{
            packageFlag: '0',
            quantity: +this.data.number,
            productSku: currency.gameCouponCode || '',
            // productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'CASH_GAME_COUPON',
          bizCode: '1161030'
        })
      } else if (this.data.type == 2) {
        request = currencyShopModel.orderUnloginUnionQuery({
          merchantId,
          items: [{
            packageFlag: '1',
            quantity: +this.data.number,
            productSku: currency.pkgCode || '',
            productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'CASH_PKG_GAME_COUPON',
          bizCode: '1131035'
        })
      } else if (this.data.payType == "PKG_SVIP") {
        request = currencyShopModel.orderUnloginUnionQuery({
          merchantId,
          items: [{
            packageFlag: '1',
            quantity: +this.data.number,
            productSku: currency.productSku || '',
            productId: currency.id,
          }],
          shopId: this.data.shopId,
          payPlatform: 'WECHAT_MALL',
          busType: 'SVIP',
          bizCode: '1131130'
        })
      } else {
        request = currencyShopModel.getUnloginOrderInfo(params)
      }
    }
    return new Promise((resolve, reject) => {
      request.then(data => {
        const orderInfo = data || {}
        this.setData({
          orderInfo,
          gifts: orderInfo.gifts || []
        })

        const payPrice = orderInfo.finalOrderPrice || 0
        const split = payPrice.toFixed(2).split('.')
        this.setData({
          productMoney: (orderInfo.originalPrice || 0).toFixed(2),
          totalMoney: {
            price: payPrice,
            int: split[0],
            float: split[1]
          },
          couponPrice: (orderInfo.couponPrice || 0).toFixed(2),
          couponDiscount: orderInfo.couponDiscount ? orderInfo.couponDiscount || 0 : '',
          fullDiscount: orderInfo.fullDiscount,
          fullDiscountPrice: orderInfo.fullDiscountPrice ? (orderInfo.fullDiscountPrice || 0).toFixed(2) : '',
          fullReduction: orderInfo.fullReduction ? (orderInfo.fullReduction || 0).toFixed(2) : ''
        })
        resolve(orderInfo)
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none'
        })
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const merchantId = wx.getStorageSync('merchantId')
    this.setData({
      shopName: options.shopName,
      shopId: options.shopId,
      shopAddress: options.shopAddress,
      currency: JSON.parse(options.currency),
      payType: options.payType || '',
      type: options.type || ''
    }, () => {
      this.getOrderInfo()
      currencyShopModel.getConfig({
        merchantId,
        shopId: options.shopId,
        dictKeys: 'viewProductSwitch'
      }).then(data => {
        if (data.viewProductSwitch == '1' && this.data.payType != "PKG_SVIP" && this.data.type != 1 && this.data.type != 2) {
          this.setData({
            numShow: true
          })
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
